Please ask about problems and questions regarding this tutorial on answers.ros.org. Don't forget to include in your question the link to this page, the versions of your OS & ROS, and also add appropriate tags. |
Iterator container
Description: This tutorial teaches you how to use the Iterator container.Tutorial Level: BEGINNER
Next Tutorial: Wrapping a SMACH container with actionlib
Overview
The iterator allows you to loop through a state or states until success conditions are met. This tutorial demonstrates how to use an iterator to sort a list of numbers into evens and odds.
The Code
Below is the full state machine, create a file called iterator_tutorial.py and copy the following code:
Could not fetch external code from 'https://raw.githubusercontent.com/eacousineau/executive_smach_tutorials/hydro-devel/smach_tutorials/examples/iterator_tutorial.py':
The Code Explained
Start by constructing the iterator, the constructor takes the following arguments:
__init__(self, outcomes, input_keys, output_keys, it=[], it_label='it_data', exhausted_outcome='exhausted')
In this example, the outcomes now include preempted, a default outcome of the iterator. The it argument is the list of objects that will be iterated over and the it_label is key that holds the current value of the of the item in the it list. The exhausted argument should be set to the preferred state machine outcome, in this example the iterator outcome is succeeded when the iterator is done looping through the it list.
Could not fetch external code from 'https://raw.githubusercontent.com/eacousineau/executive_smach_tutorials/hydro-devel/smach_tutorials/examples/iterator_tutorial.py':
Now add a container and create the states for sorting the list into even and odd. Could not fetch external code from 'https://raw.githubusercontent.com/eacousineau/executive_smach_tutorials/hydro-devel/smach_tutorials/examples/iterator_tutorial.py':
Add the container to the iterator:
Could not fetch external code from 'https://raw.githubusercontent.com/eacousineau/executive_smach_tutorials/hydro-devel/smach_tutorials/examples/iterator_tutorial.py':
Finish by adding the iterator to the top level state machine:
Could not fetch external code from 'https://raw.githubusercontent.com/eacousineau/executive_smach_tutorials/hydro-devel/smach_tutorials/examples/iterator_tutorial.py':
Running the Code
Make sure that a roscore is running:
$ roscore
Run the smach_viewer so you can see the results:
$ rosrun smach_viewer smach_viewer.py
Now run the state machine:
$ sudo chmod a+x iterator_tutorial.py $ python ./iterator_tutorial.py